﻿using System;
using Grundy.Common;

namespace Grundy.CryptographicServices
{
    public class Sha256MacProviderFactory : CustomerCryptographicServicesProviderFactory
    {
        private readonly ICustomerKeyStore _customerKeyStore;

        public Sha256MacProviderFactory(ICustomerKeyStore customerKeyStore)
        {
            _customerKeyStore = customerKeyStore;
        }

        public override CustomerCryptographicServicesProvider Get(string providerString)
        {
            var info = providerString.Split(new[] {','});
            if (!info[0].EqualsIgnoreCase("Sha256MacProvider"))
                throw new InvalidOperationException("This factory cannot be used for creating providers for type {0}".FormatWith(info[0]));
            Guid customerId;
            Guid.TryParse(info[1], out customerId);
            var customerName = info[2];

            if (customerName.IsNullOrEmpty() && customerId == default(Guid))
                throw new InvalidOperationException("Need at least one of customer id or Customer name for creating a Sha256MacProvider.");

            var customerKey = _customerKeyStore.GetCustomerKey(customerId, customerName);
            return new Sha256MacProvider(customerKey.Item3, customerKey.Item1, customerKey.Item2);
        }
    }
}